package com.touch.client.forms;
import com.touch.client.*;
import com.touch.core.*;
import com.touch.jgloo.owt.*;
public class MainMenu implements Runnable
{	
	public JGLFrame frame = new JGLFrame(Language.MAIN_MENU, 400, 300);
	public final JGLLabel lStatus = new JGLLabel(Language.STATUS + ": " + Language.CHECKING);	
	public final JGLButton bLogin = new JGLButton(Language.LOGIN, 128, 32);
	public final JGLButton bNewAccount = new JGLButton(Language.NEW_ACCOUNT, 128, 32);
	public final JGLButton bCredits = new JGLButton(Language.CREDITS, 128, 32);
	public final JGLButton bQuit = new JGLButton(Language.QUIT, 128, 32);
	
	public byte state = Constants.SERVER_CHECKING; 
	private byte oldState = Constants.SERVER_CHECKING;
	private Thread serverchecker = new Thread(this);
	public MainMenu()
	{				
		this.frame.add(lStatus);
		this.frame.add(bLogin);
		this.frame.add(bNewAccount);
		this.frame.add(bCredits);
		this.frame.add(bQuit);
		this.lStatus.setPosition(225, 256, 0);
		this.bLogin.setPosition(16, 32, 0);
		this.bNewAccount.setPosition(16, 80, 0);
		this.bCredits.setPosition(16, 128, 0);
		this.bQuit.setPosition(16, 256, 0);
		this.serverchecker.setName("Server Checker");
		this.serverchecker.setPriority(Thread.MIN_PRIORITY);
		this.serverchecker.start();
	}		
	public void applyStyleSheet(final JGLStyleSheet ss)
	{
		this.frame.applyStyleSheet(ss);
		this.bLogin.applyStyleSheet(ss);
		this.bCredits.applyStyleSheet(ss);
		this.bNewAccount.applyStyleSheet(ss);
		this.bQuit.applyStyleSheet(ss);
	}
	public void run()
	{
		while(this.state != Constants.THREAD_ENDING)
		{
			try
			{
				if(AsyncClientSocket.canReach(Database.host))
				{
					if(AsyncClientSocket.canConnect(Database.host, Database.port))
						this.state = Constants.SERVER_ONLINE;
					else
						this.state = Constants.SERVER_OFFLINE;				
				}
				else
					this.state = Constants.SERVER_UNREACHABLE;			
				Thread.sleep(60000);
			}
			catch(final Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	private void setStatus(final String status)
	{
		this.lStatus.setText(Language.STATUS + ": " + status);
	}
	private void check()
	{
		switch(this.state)
		{
			case Constants.SERVER_UNREACHABLE:				
				this.setStatus(Language.UNREACHABLE);
				break;			
			case Constants.SERVER_CHECKING:				
				this.setStatus(Language.CHECKING);
				break;
			case Constants.SERVER_OFFLINE:
				this.setStatus(Language.OFFLINE);
				break;
			case Constants.SERVER_ONLINE:
				this.setStatus(Language.ONLINE);
				break;
		}
		this.oldState = this.state;
	}
	public void render()
	{					
		if(this.state != this.oldState)
			this.check();
		
		this.frame.render();							
	}	
}
